import axios from 'axios';
import { GetCookieTOOL, DelCookieTOOL } from '@utils/index';

export default function request(method: any, url: any, body: any, option = { token: undefined }): Promise<any> {
  // 分割url
  const str = url.split('/');
  const adminKey = !str.includes('login') && str.includes('admin');
  const userKey = !str.includes('auth') && !str.includes('admin') && !str.includes('login');
  let token: null | string = null;

  if (method === 'GET') {
    body = undefined;
  }

  let headers = {};
  if (option.token) {
    headers = {
      'Content-Type': 'application/json;charset=utf-8',
      Authorization: option.token,
    };
  } else {
    headers = {
      'Content-Type': 'application/json;charset=utf-8',
    };
  }

  // url判断接口是否包含admin或auth
  if (adminKey) {
    token = GetCookieTOOL('userAdmin');
  }
  if (userKey) {
    token = GetCookieTOOL('user');
  }

  headers['token'] = token;

  return axios({
    method,
    url,
    headers,
    data: body,
  })
    .then((response) => {
      if (response.status === 504) {
        return {
          message: '后端服务未启动。',
          status: 'error',
        };
      }
      return response.data;
    })
    .then((res) => {
      if (res.status === '200' || res.status === 200) {
        // 当data 为空时返回success
        // 存在res.total字段 则返回 整个res
        // 否则只返回 res.data
        return Promise.resolve(res.data === undefined ? 'success' : res.total || res.total === 0 ? res : res.data);
      }
      return Promise.reject(res.message);
    })
    .catch((err) => {
      const res = err.response;
      if (res.status === 401) {
        // url判断接口是否包含admin或api
        if (adminKey) {
          DelCookieTOOL('userAdmin');
          DelCookieTOOL('adminName');
          window.location.reload();
        }
        if (userKey) {
          DelCookieTOOL('user');
          window.location.reload();
        }
      }
      return Promise.reject(err);
    });
}

export const get = (path: string, body?: any, option?: any): any => request('get', path, '', option);
export const del = (path: string, body: any, option?: any): any => request('delete', path, body, option);
export const post = (path: string, body: any, option?: any): any => request('post', path, body, option);
export const put = (path: string, body: any, option?: any): any => request('put', path, body, option);
